Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

203
Visualizações
How to use "indexOf" in javascript

Hi I am usin Angular and I am struggling for an issue. I would like to know How to use "indexOf()" method on a array which has two or more fields. Here is my code:

My array:

[
{
  "id":1,
  "name": "stuff",
  "surname": "stuff"
},
{
  "id":2,
  "name": "stuff",
  "surname": "stuff"
},
{
  "id":3,
  "name": "stuff",
  "surname": "stuff"
}
]

in my angular Code I would like to a user type a certain id from the template(in the form) and check if the corresponding user exists in my array. my angular code is:

      <form #formValue="ngForm" (ngSubmit)="onClick(formValue)">
             <div class="form-group">
               <label for="exampleInputEmail1">Identifiant du challenge</label>
               <input type="text" name="_id" #_id="ngModel" [(ngModel)]="this.user._id" 
                 class="form-control"  pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" 
                 placeholder="identifiant">
               
             </div>
             
              
             <input type="submit" value="Submit"  class="btn btn-primary"/>
    </form>

in my *.ts file I have a method that I perform on the submit event named "onClick" look at my ts file:

 onClick(form: NgForm){
    this.getUsers(form.value._id)
  }

// get users method

 getUsers(id: String){
     return this._http.get<any[]>(this.url + 'getAllChallenge').subscribe(
         (users)=>{
             this.users=users;

             this.checkExist= this.users.indexOf(id)
              if(this.checkExist==-1){
                  alert("this id you typed doesn't exist in our array")
               }
               else{

                  /* here is my issue. this alert if is always printed enven 
                     If I type 1,2 or 3(an 
                     existing id)*/

                  alert("this Id exist")
                 }
          
                  
              } 
     );
  }

Thank you in advance!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Basically, you don't.

The function you want to use is find().

You give it a function which should return true or false based on whatever you want. It will then return the first element that matches, or undefined if no elements do. So, if you get a match, it exists, otherwise, it doesn't. You don't have to explicitly cast to a Boolean, but you can.

this.checkExist = Boolean(this.users.find(user => user.id === id));

This is also a findIndex() method which returns the index instead of the object itself if you'd prefer that, but if you're using it as a Boolean, using find() will be safer (since you won't have to check for !== -1).

about 4 years ago · Juan Pablo Isaza Relatório

0

If you passed the object to getUsers() function, you could actually do that. I don't know if it is possible in Angular.

a={}
b={}
c=[a,b]
c.indexOf(b) // = 1

Otherwise use the find() method as suggested by others.

about 4 years ago · Juan Pablo Isaza Relatório

0

You should use findIndex()

var arr = [
{
  "id":1,
  "name": "stuff",
  "surname": "stuff"
},
{
  "id":2,
  "name": "stuff",
  "surname": "stuff"
},
{
  "id":3,
  "name": "stuff",
  "surname": "stuff"
}
]

let index = arr.findIndex((obj) => {
  return obj.id == 2
})
console.log(index)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda